package com.alks.function.service.impl.procurement;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.dto.SysUserTokenDTO;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.service.RedisService;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.beanutils.ObjectUtils;
import com.alks.common.utils.excelUtils.ExcelPoiUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.entity.data.entity.*;
import com.alks.entity.data.enums.CompanyEnum;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.chengKong.produce.PcLotHeadDto;
import com.alks.function.data.dto.chengKong.produce.PcLotUsageDto;
import com.alks.function.data.dto.procurement.*;
import com.alks.function.data.request.chengKong.PcLotHeadRequest;
import com.alks.function.data.request.procurement.SummaryRequest;
import com.alks.function.mapper.chengKong.LargeCargoUsageMapper;
import com.alks.function.mapper.chengKong.PcLotHeadMapper;
import com.alks.function.mapper.procurement.MaterialClearanceMapper;
import com.alks.function.mapper.procurement.PurCompanyMapper;
import com.alks.function.mapper.procurement.SummaryOperationMapper;
import com.alks.function.mapper.stockdept.pcfactorystockquery.SD_SQ_MpMtlSubMapper;
import com.alks.function.service.procurement.SummaryOperationService;
import com.baomidou.mybatisplus.extension.api.R;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SummaryOperationServiceImpl implements SummaryOperationService {

    @Autowired
    private SummaryOperationMapper summaryOperationMapper;

    @Autowired
    private PcLotHeadMapper pcLotHeadMapper;

    @Autowired
    private LargeCargoUsageMapper largeCargoUsageMapper;

    @Autowired
    private  SD_SQ_MpMtlSubMapper subMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private PurCompanyMapper purMapper;

    @Autowired
    private MaterialClearanceMapper materialClearanceMapper;

    /**
     * 待汇总指令：查询
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getNotSummaryLotNoList(SummaryRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        //给排序方式赋值:0是升序，1是降序
        if(request.getSortWay().equals("0")){
            request.setSortWay("ASC");
        }else{
            request.setSortWay("DESC");
        }
        List<SummaryALLDataDto> notSummaryLotNoList = summaryOperationMapper.getNotSummaryLotNoList(companyId,request);

        //用pageInfo对查询结果封装
        PageInfo list = new PageInfo(notSummaryLotNoList);
        HashMap map = new HashMap<>();
        map.put("lotNoList", notSummaryLotNoList);
        map.put("total", list.getTotal());
        return ResponseInfo.ok(map);
    }

    /**
     * 汇总号查询
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getSummaryNumberList(SummaryRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        List<SummaryDataDto> summaryNumberList = summaryOperationMapper.getSummaryNumberList(companyId, request);

        //用pageInfo对查询结果封装
        PageInfo list = new PageInfo(summaryNumberList);
        HashMap map = new HashMap<>();
        map.put("lotNoList", summaryNumberList);
        map.put("total", list.getTotal());
        return ResponseInfo.ok(map);
    }

    /**
     * 汇总指令查询
     * @return
     */
    @Override
    public ResponseInfo getSummaryLotNoList(SummaryRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        SummaryDataDto1 list = summaryOperationMapper.getSummaryLotNoList(companyId, request);
        return ResponseInfo.ok(list);
    }

    /**
     * 汇总材料查询
     * @return
     */
    @Override
    //@AutoPageAop
    public ResponseInfo getSummaryMaterialList(SummaryRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        List<SummaryDataDto2> list = summaryOperationMapper.getSummaryMaterialList(companyId, request);

        PageInfo pageList = new PageInfo(list);
        HashMap map = new HashMap<>();
        map.put("lotNoList", list);
        map.put("total", pageList.getTotal());
        return ResponseInfo.ok(map);
    }

    /**
     * 汇总指令材料明细查询
     * @return
     */
    @Override
    public ResponseInfo getSummaryDetailList(SummaryRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        List<SummaryDataDto3> list = summaryOperationMapper.getSummaryDetailList(companyId, request);
        return ResponseInfo.ok(list);
    }

    /**
     * 贴合子材料查询
     * @return
     */
    @Override
    public ResponseInfo getBondingSubmaterial(SummaryRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        List<SummaryDataDto4> list = summaryOperationMapper.getBondingSubmaterial(companyId, request);
        return ResponseInfo.ok(list);
    }

    /**
     * 删除指令资料查询
     * @return
     */
    @Override
    public ResponseInfo getDeleteLotNoList() {
        String companyId = UserIdThread.get().getCompanyId();
        List<String> list = summaryOperationMapper.getDeleteLotNoList(companyId);
        return ResponseInfo.ok(list);
    }

    /**
     * 删除指令资料查询：恢复指令
     * @return
     */
    @Override
    public ResponseInfo recoverLotNo(String lotNo) {
        String companyId = UserIdThread.get().getCompanyId();
//        if(summaryOperationMapper.getDeleteLotNo(companyId,lotNo) <= 0){
//            throw new ServiceErrorException("该指令不存在");
//        }
        int count = summaryOperationMapper.recoverLotNo(companyId, lotNo);
        if(count > 0){
            return ResponseInfo.ok("指令"+ lotNo+ "恢复成功");
        }else{
            throw new ServiceErrorException( "指令恢复失败");
        }
    }

    /**
     * 不汇总指令删除
     * @param lotNo
     * @return
     */
    @Override
    public ResponseInfo deleteNotSummaryLotNo(String lotNo) {
        String companyId = UserIdThread.get().getCompanyId();
        int count = summaryOperationMapper.deleteNotSummaryLotNo(companyId, lotNo);

        if(count > 0){
            return ResponseInfo.ok("不汇总指令"+ lotNo+ "删除成功");
        }else{
            throw new ServiceErrorException("不汇总指令删除失败");
        }
    }

    /**
     * 汇总删除
     * @param sumNo
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo deleteSummaryLotNo(String sumNo) {
        /*判断*/
        //1.汇总已在处理，不能删除：已经订购
       //如果在pc042中的pur_falg为Y的不能删

        String companyId = UserIdThread.get().getCompanyId();
        Pc040 pc040 = summaryOperationMapper.getSummaryNumberBySumNo(companyId, sumNo);
        Pc041 pc041 = summaryOperationMapper.getSummaryLotNoBySumNo(companyId, sumNo);
        List<Pc042> list2 = summaryOperationMapper.getSummaryMaterialBySumNo(companyId, sumNo);
        if(ObjectUtils.isNotEmpty(list2)) {
            boolean b = list2.stream()
                    .filter(Objects::nonNull)
                    .anyMatch(pc042 -> Optional.ofNullable(pc042.getPurFlag()).orElse("").equals("Y")); // 检查 purFlag 是否为 "Y"
            if(b){
                throw new ServiceErrorException("汇总已在处理，不能删除！");
            }
        }

        List<Pc043> pc043 = summaryOperationMapper.getSummaryDetailListBySumNo(companyId, sumNo);
        List<Pc044> pc044 = summaryOperationMapper.getBondingSubmaterialBySumNo(companyId, sumNo);

        int count0 = summaryOperationMapper.deletePc040(pc040);
        int count1 = summaryOperationMapper.deletePc041(pc041);
        int count2 = summaryOperationMapper.deletePc042(list2);
        int count3 = summaryOperationMapper.deletePc043(pc043);
        if(ObjectUtils.isNotEmpty(pc044)){
            int count4 = summaryOperationMapper.deletePc044(pc044);
        }
        if(count0>0 && count1>0 && count2>0 && count3>0){
            return ResponseInfo.ok("汇总删除成功");
        }else{
            throw new ServiceErrorException("汇总删除失败");
        }

    }

    /**
     * 汇总作业
     *
     */
    @Override
    @Transactional
    public ResponseInfo summaryOperation(SummaryALLDataDto request) {
        /*判断*/
        //已经生成的汇总不能再汇总
        if(request.getSumNo() != null){
            throw new ServiceErrorException("该指令已经生成汇总号，不能再汇总");
        }

        //1.生成汇总号
        //先查询当时最大汇总号
        String companyId = UserIdThread.get().getCompanyId();
        SysUserTokenDTO dto = UserIdThread.get();
        String userName = UserIdThread.get().getUserName();

        String time = "yyMMdd";
        String key = "SummaryOperation/summaryOperation" + companyId + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMM"));
        String prefix = generatePrefix(key, "3", time);
        String sumNo = CompanyEnum.updateId(companyId) + prefix;
        request.setSumNo(sumNo);

        //2.查出来源数据
        //一》指令明细
        PcLotHeadRequest pcLotHeadRequest = new PcLotHeadRequest();
        pcLotHeadRequest.setLotNo(request.getLotNo());
        List<PcLotHeadDto> styleDetails = pcLotHeadMapper.getStyleDetails(pcLotHeadRequest, dto);
        //二》指令用量明细
//        List<PcLotUsageDto> usageDetails = pcLotHeadMapper.getUsageDetails(request.getLotNo());
        //合并查询汇总材料：指令明细和明细子材料(和可以请购的贴合)在一起放入pc042里面的(以前子材料用的：SD_BOM_FIT_SUB，现在改PC_LOT_USAGE_FIT)
        List<PcLotUsageDto> usageAndSubMaterial = pcLotHeadMapper.getUsageAndSubMaterial(request.getLotNo(),companyId);
        List<String> mtlNoList = usageAndSubMaterial.stream().map(PcLotUsageDto::getMtlNo).collect(Collectors.toList());
        //三》贴合子材料明细
        List<SdBomFitSubDto> subList = largeCargoUsageMapper.getDetailsOfAdhesiveSubMaterialBymtlNoList(mtlNoList,companyId,request.getLotNo());
//        List<FdMtlSumDto> subList = subMapper.getFdMtlSumQuery(null, request.getLotNo(), mtlNo);
//        List<FdMtlSubDto> subList = subMapper.getBatchFdMtlSumQuery(null, request.getLotNo(), mtlNoList,companyId);

        //3.复制给pc040
        Pc040 pc040 = new Pc040();
        pc040.setCompanyId(companyId);
        pc040.setSumNo(request.getSumNo());
        pc040.setSysDate(new Date());
        pc040.setSysUser(userName);
        pc040.setLotNo(request.getLotNo());
        int count = summaryOperationMapper.addPc040(pc040);
        //4.复制给pc041
        Pc041 pc041 = new Pc041();
        pc041.setCompanyId(companyId);
        pc041.setSumNo(request.getSumNo());
        pc041.setLotNo(request.getLotNo());
        pc041.setLotType(request.getLotType());
        if (ObjectUtils.isNotEmpty(styleDetails)) {
            pc041.setOrderQty(styleDetails.get(0).getOrderQty());
            pc041.setSurplusQty(styleDetails.get(0).getSurplusQty());
        }
        int count1 = summaryOperationMapper.addPc041(pc041);
        //5.复制给pc042
        //6.复制给pc043
        List<Pc042> pc042List = new ArrayList<>();
        List<Pc043> pc043List = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(usageAndSubMaterial)) {
            for (PcLotUsageDto usageDetail : usageAndSubMaterial) {
                //向上取整：数量
                BigDecimal ttlUsage = usageDetail.getTtlUsage();
                // 检查ttlUsage是否为整数
                boolean isInteger = ttlUsage.scale() <= 0 || ttlUsage.stripTrailingZeros().scale() <= 0;
                // 如果ttlUsage不是整数，进行向上取整
                BigDecimal roundedTtlUsage = isInteger ? ttlUsage : ttlUsage.setScale(0, RoundingMode.CEILING);

                //封装pc042
                Pc042 pc042 = new Pc042();
                pc042.setCompanyId(companyId);
                pc042.setSumNo(request.getSumNo());
                pc042.setMtlNo(usageDetail.getMtlNo());
                pc042.setMtlName(usageDetail.getMtlName());
                pc042.setMtlSpec(usageDetail.getMtlSpec());
                pc042.setMtlUnit(usageDetail.getMtlUnit());
                pc042.setMtlColor(usageDetail.getMtlColor());
                pc042.setLotDetail(request.getLotNo());
                //数量
                pc042.setTtlUsage(roundedTtlUsage);
                pc042.setActUsage(roundedTtlUsage);
                pc042.setAdvanceUsage(usageDetail.getAddUsage());
                pc042.setSubUsage(null);    //暂时不知道数据哪里来的
                pc042List.add(pc042);

                //封装pc043
                Pc043 pc043 = new Pc043();
                pc043.setCompanyId(companyId);
                pc043.setSumNo(request.getSumNo());
                pc043.setMtlNo(usageDetail.getMtlNo());
                pc043.setMtlName(usageDetail.getMtlName());
                pc043.setMtlSpec(usageDetail.getMtlSpec());
                pc043.setMtlUnit(usageDetail.getMtlUnit());
                pc043.setMtlColor(usageDetail.getMtlColor());
                pc043.setLotNo(request.getLotNo());
                pc043.setLotDetail(request.getLotNo());
                pc043.setLotType(request.getLotType());
                //数量
                pc043.setTtlUsage(ttlUsage);
                pc043.setActUsage(ttlUsage);
                pc043.setAdvanceUsage(usageDetail.getAddUsage());
                pc043.setSubUsage(null);    //暂时不知道数据哪里来的
                pc043List.add(pc043);
            }
        }
        int count2 = summaryOperationMapper.addPc042(pc042List);
        int count3 = summaryOperationMapper.addPc043(pc043List);
        //6.复制给pc044
        List<Pc044> pc044List = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(subList)) {
            for (SdBomFitSubDto sub : subList) {
                //贴合子材料只有有清购标识的才会汇总进去
                Pc044 pc044 = new Pc044();
                pc044.setCompanyId(companyId);
                pc044.setSumNo(request.getSumNo());
                pc044.setLotNo(request.getLotNo());
                pc044.setLotType(request.getLotType());
                pc044.setMtlNo(sub.getMtlNo());
                pc044.setMtlName(sub.getMtlName());
                pc044.setMtlUnit(sub.getMtlUnit());
                pc044.setMtlColor(sub.getMtlColor());
                pc044.setMtlSpec(sub.getMtlSpec());
                pc044.setSubMtlNo(sub.getSubMtlNo());
                pc044.setSubMtlName(sub.getSubMtlName());
                pc044.setSubMtlUnit(sub.getSubMtlUnit());
                pc044.setSubMtlColor(sub.getSubMtlColor());
                pc044.setSubMtlSpec(sub.getSubMtlSpec());
                //向上取整：数量
                BigDecimal ttlUsage = sub.getTtlUsage();
                // 检查ttlUsage是否为整数
                boolean isInteger = ttlUsage.scale() <= 0 || ttlUsage.stripTrailingZeros().scale() <= 0;
                // 如果ttlUsage不是整数，进行向上取整
                BigDecimal roundedTtlUsage = isInteger ? ttlUsage : ttlUsage.setScale(0, RoundingMode.CEILING);
                //填充数量
                pc044.setTtlUsage(null);
                pc044.setSubTtlUsage(roundedTtlUsage);
                //贴合子材料的预加量先不管
                pc044.setAdvanceUsage(sub.getAddUsage());
                pc044List.add(pc044);
            }
        }
        if(ObjectUtils.isNotEmpty(pc044List)){
            int count4 = summaryOperationMapper.addPc044(pc044List);
        }
        if (count > 0 && count1 > 0 && count2 > 0 && count3 > 0 ) {
            return ResponseInfo.ok("汇总作业完成，汇总号："+ request.getSumNo());
        } else {
            throw new ServiceErrorException("汇总作业失败");
        }

    }

    /**
     * 导出订购单
     * @param sumNo
     * @param response
     */
    @Override
    public void exportSummaryMaterialDetail(List<String> sumNo, HttpServletResponse response) throws IOException {
        String fileName = "汇总材料明细表_" + DateUtils.dateTimeNow() + ".xlsx";
        String companyId = UserIdThread.get().getCompanyId();

        //公司名字
        PurCompany companyDto = purMapper.findPurCompanyInfo(companyId);
        //汇总数据
        List<ExportSummaryDataDto> list =  summaryOperationMapper.queryExportSummaryMaterialDetail(companyId, sumNo);

        HashMap map = new HashMap<>();
        map.put("c", companyDto);
        map.put("list", list);

        try {
            ExcelUtils.setResponseZF(response, fileName);
            String templatePath =  "templates/汇总材料明细表模板.xls" ;
            ExcelPoiUtils.writeExcelList(response, map, templatePath, fileName);
        } catch (Exception e) {
            log.error("汇总材料明细表导出失败, 错误信息: {}", e.getMessage());
        }

    }

    /**
     * 汇总作业:批量
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo summaryOperationBatch(List<SummaryALLDataDto> requests) {
        /*判断*/
        String companyId = UserIdThread.get().getCompanyId();
        String userName = UserIdThread.get().getUserName();
        //1.相同材料编码不一样：要对汇总数据进行判断，如果某个指令的材料有材料名称一样，但是编码不同的指令会报错
        List<String> lotList = requests.stream().map(SummaryALLDataDto::getLotNo).collect(Collectors.toList());
        List<PcLotUsageDto> judeList = pcLotHeadMapper.judgeUsageAndSubMaterial(lotList, companyId);
        if (ObjectUtils.isNotEmpty(judeList)){
            StringBuilder lotNosBuilder = new StringBuilder();
            for (PcLotUsageDto judeData : judeList) {
                if (lotNosBuilder.length() > 0) {
                    lotNosBuilder.append("、"); // 使用中文的顿号
                }
                lotNosBuilder.append(judeData.getLotNo());
            }
            String lotNos = lotNosBuilder.toString();
            throw new ServiceErrorException(lotNos + "指令存在相同材料有不同物料编码的情况，请联系IT进行修改");
        }

        //2.判断错误编码的情况：有颜色的情况
        //1>>批量查询 PC_LOT_USAGE 中有没有错误数据
        List<CleanDataDto> list1 = summaryOperationMapper.cleanPcLotUsageBatch(companyId, lotList);
        //2>>批量查询 SD_BOM_FIT_SUB 中有没有错误数据
        List<CleanDataDto> list2 = summaryOperationMapper.cleanSdBomFitSubBatch(companyId, lotList);
        Set<String> lotNosSet = new HashSet<>();
        // 提取 list1 中的 lotNo 并去重
        if (ObjectUtils.isNotEmpty(list1)) {
            for (CleanDataDto data : list1) {
                lotNosSet.add(data.getLotNo());
            }
        }
        // 提取 list2 中的 lotNo 并去重
        if (ObjectUtils.isNotEmpty(list2)) {
            for (CleanDataDto data : list2) {
                lotNosSet.add(data.getLotNo());
            }
        }
        // 拼接 lotNo 字符串
        String lotNos = StringUtils.join(lotNosSet, "、");
        if (ObjectUtils.isNotEmpty(lotNos)) {
            throw new ServiceErrorException(lotNos + "指令存在错误的物料编码，请联系IT进行修改");
        }

        SysUserTokenDTO dto = UserIdThread.get();
        /*处理汇总数据*/
        try {
        List<String> successfulSummaries = new ArrayList<>();
        for (SummaryALLDataDto request : requests) {
                //1.生成汇总号
                String time = "yyMMddHH";
                String key = "SummaryOperation/summaryOperation" + companyId + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMM"));//自增数字里面加上年月
                String prefix = generatePrefix(key, "3", time);
                String sumNo = CompanyEnum.updateId(companyId) + prefix;
                request.setSumNo(sumNo);

                //2.查出来源数据
                PcLotHeadRequest pcLotHeadRequest = new PcLotHeadRequest();
                pcLotHeadRequest.setLotNo(request.getLotNo());
                List<PcLotHeadDto> styleDetails = pcLotHeadMapper.getStyleDetails(pcLotHeadRequest, dto);
                //查询子材料和贴合子材料汇总
                List<PcLotUsageDto> usageAndSubMaterial = pcLotHeadMapper.getUsageAndSubMaterial2(request.getLotNo(), companyId); //SD_BOM_FIT_SUB 换成 PC_LOT_USAGE_FIT 表
                //查询子材料匹配的贴合材料  >>SD_BOM_FIT_SUB 换成 PC_LOT_USAGE_FIT 表
                List<String> mtlNoList = usageAndSubMaterial.stream().map(PcLotUsageDto::getMtlNo).collect(Collectors.toList());
                //List<SdBomFitSubDto> subList = largeCargoUsageMapper.getDetailsOfAdhesiveSubMaterialBymtlNoList(mtlNoList, companyId, request.getLotNo());
               List<SdBomFitSubDto> subList = largeCargoUsageMapper.getPcLotUsageFit(companyId, request.getLotNo());

                //3.复制给pc040
                Pc040 pc040 = new Pc040();
                pc040.setCompanyId(companyId);
                pc040.setSumNo(request.getSumNo());
                pc040.setSysDate(new Date());
                pc040.setSysUser(userName);
                pc040.setLotNo(request.getLotNo());
                int count = summaryOperationMapper.addPc040(pc040);

                //4.复制给pc041
                Pc041 pc041 = new Pc041();
                pc041.setCompanyId(companyId);
                pc041.setSumNo(request.getSumNo());
                pc041.setLotNo(request.getLotNo());
                pc041.setLotType(request.getLotType());
                if (ObjectUtils.isNotEmpty(styleDetails)) {
                    pc041.setOrderQty(styleDetails.get(0).getOrderQty());
                    pc041.setSurplusQty(styleDetails.get(0).getSurplusQty());
                }
                int count1 = summaryOperationMapper.addPc041(pc041);

                //5.复制给pc042
                List<Pc042> pc042List = new ArrayList<>();
                if (ObjectUtils.isNotEmpty(usageAndSubMaterial)) {
                    for (PcLotUsageDto usageDetail : usageAndSubMaterial) {
                        //向上取整：数量
                        BigDecimal ttlUsage = usageDetail.getTtlUsage();
                        // 检查ttlUsage是否为整数
                        boolean isInteger = ttlUsage.scale() <= 0 || ttlUsage.stripTrailingZeros().scale() <= 0;
                        // 如果ttlUsage不是整数，进行向上取整
                        BigDecimal roundedTtlUsage = isInteger ? ttlUsage : ttlUsage.setScale(0, RoundingMode.CEILING);

                        Pc042 pc042 = new Pc042();
                        pc042.setCompanyId(companyId);
                        pc042.setSumNo(request.getSumNo());
                        pc042.setMtlNo(usageDetail.getMtlNo());
                        pc042.setMtlName(usageDetail.getMtlName());
                        pc042.setMtlSpec(usageDetail.getMtlSpec());
                        pc042.setMtlUnit(usageDetail.getMtlUnit());
                        pc042.setMtlColor(usageDetail.getMtlColor());
                        pc042.setLotDetail(request.getLotNo());
                        //数量
                        pc042.setTtlUsage(roundedTtlUsage);
                        pc042.setActUsage(roundedTtlUsage);
                        pc042.setAdvanceUsage(usageDetail.getAddUsage());
                        pc042.setSubUsage(null);    //暂时不知道数据哪里来的
                        pc042List.add(pc042);
                    }
                }
                int count2 = summaryOperationMapper.addPc042(pc042List);

                //6.复制给pc043
                List<Pc043> pc043List = new ArrayList<>();
                if (ObjectUtils.isNotEmpty(usageAndSubMaterial)) {
                    for (PcLotUsageDto usageDetail : usageAndSubMaterial) {
                        Pc043 pc043 = new Pc043();
                        pc043.setCompanyId(companyId);
                        pc043.setSumNo(request.getSumNo());
                        pc043.setMtlNo(usageDetail.getMtlNo());
                        pc043.setMtlName(usageDetail.getMtlName());
                        pc043.setMtlSpec(usageDetail.getMtlSpec());
                        pc043.setMtlUnit(usageDetail.getMtlUnit());
                        pc043.setMtlColor(usageDetail.getMtlColor());
                        pc043.setLotNo(request.getLotNo());
                        pc043.setLotDetail(request.getLotNo());
                        pc043.setLotType(request.getLotType());
                        //数量
                        pc043.setTtlUsage(usageDetail.getTtlUsage());
                        pc043.setActUsage(usageDetail.getTtlUsage());
                        pc043.setAdvanceUsage(usageDetail.getAddUsage());
                        pc043.setSubUsage(null);    //暂时不知道数据哪里来的
                        pc043List.add(pc043);
                    }
                }
                int count3 = summaryOperationMapper.addPc043(pc043List);

                //6.复制给pc044
                List<Pc044> pc044List = new ArrayList<>();
                if (ObjectUtils.isNotEmpty(subList)) {
                    for (SdBomFitSubDto sub : subList) {
                        Pc044 pc044 = new Pc044();
                        pc044.setCompanyId(companyId);
                        pc044.setSumNo(request.getSumNo());
                        pc044.setLotNo(request.getLotNo());
                        pc044.setLotType(request.getLotType());
                        pc044.setMtlNo(sub.getMtlNo());
                        pc044.setMtlName(sub.getMtlName());
                        pc044.setMtlUnit(sub.getMtlUnit());
                        pc044.setMtlColor(sub.getMtlColor());
                        pc044.setMtlSpec(sub.getMtlSpec());
                        pc044.setSubMtlNo(sub.getSubMtlNo());
                        pc044.setSubMtlName(sub.getSubMtlName());
                        pc044.setSubMtlUnit(sub.getSubMtlUnit());
                        pc044.setSubMtlColor(sub.getSubMtlColor());
                        pc044.setSubMtlSpec(sub.getSubMtlSpec());
                        //向上取整：数量
                        BigDecimal ttlUsage = sub.getTtlUsage();
                        // 检查ttlUsage是否为整数
                        boolean isInteger = ttlUsage.scale() <= 0 || ttlUsage.stripTrailingZeros().scale() <= 0;
                        // 如果ttlUsage不是整数，进行向上取整
                        BigDecimal roundedTtlUsage = isInteger ? ttlUsage : ttlUsage.setScale(0, RoundingMode.CEILING);
                        //填充数量
                        pc044.setTtlUsage(null);
                        pc044.setSubTtlUsage(roundedTtlUsage); //贴合子材料数量
                        //贴合子材料的预加量先不管
                        pc044.setAdvanceUsage(sub.getAddUsage());
                        pc044List.add(pc044);
                    }
                }
                if (ObjectUtils.isNotEmpty(pc044List)) {
                    int count4 = summaryOperationMapper.addPc044(pc044List);
                }

                if (count > 0 && count1 > 0 && count2 > 0 && count3 > 0) {
                    successfulSummaries.add(request.getSumNo());
                } else {
                    throw new ServiceErrorException("汇总作业异常，异常指令号：" + request.getLotNo());
                }
            }
            return  ResponseInfo.ok("汇总成功：" + String.join("、", successfulSummaries));
        } catch (ServiceErrorException se) {
            log.error("汇总作业异常，异常指令号：" + se.getMessage(), se);
            throw se;
        } catch (Exception e) {
            log.error("汇总作业异常，请检查", e);
            throw new ServiceErrorException("汇总作业异常，请联系IT检查");
        }
    }

    /**
     * PC_LOT_USAGE 和 SD_BOM_FIT_SUB 和 PC_LOT_USAGE_FIT
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo cleanNoSummaryData(String lotNo) {
        /*判空*/
        if (StringUtils.isEmpty(lotNo)){
            throw new ServiceErrorException("指令不能为空");
        }

        String companyId = UserIdThread.get().getCompanyId();
        //1.清洗 PC_LOT_USAGE
        //查询 PC_LOT_USAGE 中有没有错误编码
        boolean a = false;
        List<CleanDataDto> list1 = summaryOperationMapper.cleanPcLotUsage(companyId,lotNo);
        if(ObjectUtils.isNotEmpty(list1) && list1.size() > 0){
            //清洗PC_LOT_USAGE数据
            int count1 = pcLotHeadMapper.cleanPcLotUsage(companyId,list1);
            a = count1 > 0;
        }

        //2.清洗 SD_BOM_FIT_SUB
        //查询SD_BOM_FIT_SUB中有没有错误数据
        boolean b = false;
        List<CleanDataDto> list2 = summaryOperationMapper.cleanSdBomFitSub(companyId,lotNo);
        //有的话清洗
        if(ObjectUtils.isNotEmpty(list2) && list2.size() > 0){
            //清洗SD_BOM_FIT_SUB数据
            int count2 = largeCargoUsageMapper.cleanSdBomFitSub(companyId,list2);
            b = count2 > 0;
        }

        //3.清洗 PC_LOT_USAGE_FIT
        boolean d = false;
        List<CleanDataDto> list3 = summaryOperationMapper.cleanPcLotUsageFit(companyId,lotNo);
        //有的话清洗
        if (list3 != null && !list3.isEmpty()) {
            //清洗 PC_LOT_USAGE_FIT 数据
            int count3 = pcLotHeadMapper.cleanPcLotUsageFit(companyId,list3);
            d = count3 > 0;
        }

        //如过有数据就清洗成功的就提示成功
        if( a || b || d){
            return ResponseInfo.ok("指令：" + lotNo + " 清洗成功");
        }else{
            throw new ServiceErrorException("指令：" + lotNo + " 清洗失败或无材料编码异常");
        }
    }

    /**根据指令数据清洗( PC_LOT_USAGE 和 SD_BOM_FIT_SUB 和 PC_LOT_USAGE_FIT)-批量2
     * @param lotNos
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo cleanNoSummaryDataBatch2(List<String> lotNos) {
        /*判空*/
        if (lotNos == null || lotNos.isEmpty()) {
            throw new ServiceErrorException("请选择数据");
        }

        String companyId = UserIdThread.get().getCompanyId();
        //1.清洗 PC_LOT_USAGE
        //查询 PC_LOT_USAGE 中有没有错误编码
        boolean a = false;
        List<CleanDataDto> list1 = summaryOperationMapper.cleanPcLotUsageBatch(companyId,lotNos);
        if(ObjectUtils.isNotEmpty(list1) && list1.size() > 0){
            //清洗PC_LOT_USAGE数据
            int count1 = pcLotHeadMapper.cleanPcLotUsage(companyId,list1);
            a = count1 > 0;
        }

        //2.清洗 SD_BOM_FIT_SUB
        //查询SD_BOM_FIT_SUB中有没有错误数据
        boolean b = false;
        List<CleanDataDto> list2 = summaryOperationMapper.cleanSdBomFitSub2();
        //有的话清洗
        if(ObjectUtils.isNotEmpty(list2) && list2.size() > 0){
            //清洗SD_BOM_FIT_SUB数据
            int count2 = largeCargoUsageMapper.cleanSdBomFitSub(companyId,list2);
            b = count2 > 0;
        }

        //3.清洗 PC_LOT_USAGE_FIT
        boolean d = false;
        List<CleanDataDto> list3 = summaryOperationMapper.cleanPcLotUsageFitBatch(companyId,lotNos);
        //有的话清洗
        if (list3 != null && !list3.isEmpty()) {
            //清洗 PC_LOT_USAGE_FIT 数据
            int count3 = pcLotHeadMapper.cleanPcLotUsageFit(companyId,list3);
            d = count3 > 0;
        }

        //如过有数据就清洗成功的就提示成功
        if( a || b || d){
            return ResponseInfo.ok( "清洗成功");
        }else{
            throw new ServiceErrorException( "清洗失败或无材料编码异常");
        }
    }

    /**
     * 采购汇总作业：单独清洗SD_BOM_FIT_SUB
     * @return
     */
    @Override
    public ResponseInfo cleanNoSummaryData2() {
        //查询SD_BOM_FIT_SUB中有没有错误数据
        boolean b = false;
        List<CleanDataDto> list2 = summaryOperationMapper.cleanSdBomFitSub2();
        //有的话清洗
        if(ObjectUtils.isNotEmpty(list2) && list2.size() > 0){
            //清洗SD_BOM_FIT_SUB数据
            int count2 = largeCargoUsageMapper.cleanSdBomFitSub(null,list2);
            b = count2 > 0;
        }

        return ResponseInfo.ok( " 清洗成功");
    }

    /**
     * 单独清洗YF_BOM_FIT_SUB
     * @return
     */
    @Override
    public ResponseInfo cleanNoSummaryData3() {
        //查询YF_BOM_FIT_SUB中有没有错误数据
        boolean b = false;
        List<CleanDataDto> list2 = summaryOperationMapper.cleanYFBomFitSub2();
        //有的话清洗
        if(ObjectUtils.isNotEmpty(list2) && list2.size() > 0){
            //清洗YF_BOM_FIT_SUB数据
            int count2 = largeCargoUsageMapper.cleanYFBomFitSub(null,list2);
            b = count2 > 0;
        }

        return ResponseInfo.ok( " 清洗成功");
    }

    /**
     * 采购请购：清洗差异表PC_LOT_USAGE_CHG和PC_LOT_USAGE_FIT_CHG
     * @param lotNo
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo cleanNoSummaryData4(String lotNo) {
        try {
            /*PC_LOT_USAGE_CHG*/
            //1.查询PC_LOT_USAGE_CHG中有没有错误数据
            List<CleanDataDto> list1 = summaryOperationMapper.getErrorPcLotUsageChg(lotNo);
            //2.有的话清洗PC_LOT_USAGE_CHG
            if (ObjectUtils.isNotEmpty(list1) && list1.size() > 0) {
                int count1 = largeCargoUsageMapper.cleanPcLotUsageChg(lotNo, list1);
            }

            /*PC_LOT_USAGE_FIT_CHG*/
            //1.查询PC_LOT_USAGE_FIT_CHG中有没有错误数据
            List<CleanDataDto> list2 = summaryOperationMapper.getErrorPcLotUsageFitChg(lotNo);
            //2.有的话清洗PC_LOT_USAGE_FIT_CHG
            if (ObjectUtils.isNotEmpty(list2) && list2.size() > 0) {
                int count2 = largeCargoUsageMapper.cleanPcLotUsageFitChg(lotNo, list2);
            }

            /*MP_PUR_DIS*/
            //1.查询MP_PUR_DIS中有没有错误数据
            List<CleanDataDto> list3 = summaryOperationMapper.getErrorMpPurDis(lotNo);
            //2.有的话清洗MP_PUR_DIS
            if (ObjectUtils.isNotEmpty(list3) && list3.size() > 0) {
                int count3 = largeCargoUsageMapper.cleanMpPurDis(lotNo, list3);
            }

            return ResponseInfo.ok(" 清洗成功");

        }catch(Exception e){
            log.error("指令：" + lotNo + " 清洗异常", e);
            throw new ServiceErrorException("指令：" + lotNo + " 清洗异常，请联系IT检查");
        }
    }

    /**
     * 采购请购：清洗订单表表MP_PUR_DIS
     * @param lotNo
     * @return
     */
    @Override
    public ResponseInfo cleanNoSummaryData5(String lotNo) {
        return null;
    }

    /*采购汇总作业：待汇总指令数据清洗-批量*/
    @Override
    public ResponseInfo cleanNoSummaryDataBatch(List<String> request) {
        if(ObjectUtils.isEmpty(request)){
            for (String lotNo : request) {
                String companyId = UserIdThread.get().getCompanyId();
                //1.清洗PC_LOT_USAGE
                //查询PC_LOT_USAGE中有没有错误编码
                boolean a = false;
                List<CleanDataDto> list1 = summaryOperationMapper.cleanPcLotUsage(companyId,lotNo);
                if(ObjectUtils.isNotEmpty(list1) && list1.size() > 0){
                    //清洗PC_LOT_USAGE数据
                    int count1 = pcLotHeadMapper.cleanPcLotUsage(companyId,list1);
                    a = count1 > 0;
                }

                //2.清洗SD_BOM_FIT_SUB
                //查询SD_BOM_FIT_SUB中有没有错误数据
                boolean b = false;
                List<CleanDataDto> list2 = summaryOperationMapper.cleanSdBomFitSub(companyId,lotNo);
                //有的话清洗
                if(ObjectUtils.isNotEmpty(list2) && list2.size() > 0){
                    //清洗SD_BOM_FIT_SUB数据
                    int count2 = largeCargoUsageMapper.cleanSdBomFitSub(companyId,list2);
                    b = count2 > 0;
                }
            }
        }
        return ResponseInfo.ok( " 清洗成功");
    }
//
//    /**
//     * 采购汇总作业：数据平移
//     * @param lotNo
//     * @return
//     */
//    @Override
//    public ResponseInfo summaryDataExchange(String lotNo) {
//        String companyId = UserIdThread.get().getCompanyId();
//        String userName = UserIdThread.get().getUserName();
//        /*一、先把要重新汇总的数据查出基础信息*/
//        List<SummaryALLDataDto> LotNoList = summaryOperationMapper.getNotSummaryLotNoList2(companyId,lotNo);
//
//        /*二、取最新的汇总数据*/
//        if(ObjectUtils.isEmpty(LotNoList)){
//            throw new ServiceErrorException("没有查到指令数据");
//        }
//        SummaryALLDataDto request = LotNoList.get(0);
//        //1.生成汇总号
//        //先查询当时最大汇总号
//        String time = "yyMMddHH";
//        String key = "SummaryOperation/summaryOperation" + companyId;
//        String prefix = generatePrefix(key, "3", time);
//        String sumNo = companyId + prefix;
//        request.setSumNo(sumNo);
//
//        //2.查出来源数据
//        //一》指令明细
//        PcLotHeadRequest pcLotHeadRequest = new PcLotHeadRequest();
//        pcLotHeadRequest.setLotNo(request.getLotNo());
//        List<PcLotHeadDto> styleDetails = pcLotHeadMapper.getStyleDetails(pcLotHeadRequest, companyId);
//        //二》指令用量明细
////        List<PcLotUsageDto> usageDetails = pcLotHeadMapper.getUsageDetails(request.getLotNo());
//        //合并查询汇总材料：指令明细和明细子材料(和可以请购的贴合)在一起放入pc042里面的(以前子材料用的：SD_BOM_FIT_SUB，现在改PC_LOT_USAGE_FIT)
//        List<PcLotUsageDto> usageAndSubMaterial = pcLotHeadMapper.getUsageAndSubMaterial(request.getLotNo(),companyId);
//        List<String> mtlNoList = usageAndSubMaterial.stream().map(PcLotUsageDto::getMtlNo).collect(Collectors.toList());
//        //三》贴合子材料明细
//        List<SdBomFitSubDto> subList = largeCargoUsageMapper.getDetailsOfAdhesiveSubMaterialBymtlNoList(mtlNoList,companyId,request.getLotNo());
////        List<FdMtlSumDto> subList = subMapper.getFdMtlSumQuery(null, request.getLotNo(), mtlNo);
////        List<FdMtlSubDto> subList = subMapper.getBatchFdMtlSumQuery(null, request.getLotNo(), mtlNoList,companyId);
//
//        //3.复制给pc040
//        Pc040 pc040 = new Pc040();
//        pc040.setCompanyId(companyId);
//        pc040.setSumNo(request.getSumNo());
//        pc040.setSysDate(new Date());
//        pc040.setSysUser(userName);
//        pc040.setLotNo(request.getLotNo());
//        int count = summaryOperationMapper.addPc040(pc040);
//        //4.复制给pc041
//        Pc041 pc041 = new Pc041();
//        pc041.setCompanyId(companyId);
//        pc041.setSumNo(request.getSumNo());
//        pc041.setLotNo(request.getLotNo());
//        pc041.setLotType(request.getLotType());
//        if (ObjectUtils.isNotEmpty(styleDetails)) {
//            pc041.setOrderQty(styleDetails.get(0).getOrderQty());
//            pc041.setSurplusQty(styleDetails.get(0).getSurplusQty());
//        }
//        int count1 = summaryOperationMapper.addPc041(pc041);
//        //5.复制给pc042
//        //6.复制给pc043
//        List<Pc042> pc042List = new ArrayList<>();
//        List<Pc043> pc043List = new ArrayList<>();
//        if (ObjectUtils.isNotEmpty(usageAndSubMaterial)) {
//            for (PcLotUsageDto usageDetail : usageAndSubMaterial) {
//                //向上取整：数量
//                BigDecimal ttlUsage = usageDetail.getTtlUsage();
//                // 检查ttlUsage是否为整数
//                boolean isInteger = ttlUsage.scale() <= 0 || ttlUsage.stripTrailingZeros().scale() <= 0;
//                // 如果ttlUsage不是整数，进行向上取整
//                BigDecimal roundedTtlUsage = isInteger ? ttlUsage : ttlUsage.setScale(0, RoundingMode.CEILING);
//
//                //封装pc042
//                Pc042 pc042 = new Pc042();
//                pc042.setCompanyId(companyId);
//                pc042.setSumNo(request.getSumNo());
//                pc042.setMtlNo(usageDetail.getMtlNo());
//                pc042.setMtlName(usageDetail.getMtlName());
//                pc042.setMtlSpec(usageDetail.getMtlSpec());
//                pc042.setMtlUnit(usageDetail.getMtlUnit());
//                pc042.setMtlColor(usageDetail.getMtlColor());
//                pc042.setLotDetail(request.getLotNo());
//                //数量
//                pc042.setTtlUsage(roundedTtlUsage);
//                pc042.setActUsage(roundedTtlUsage);
//                pc042.setAdvanceUsage(usageDetail.getAddUsage());
//                pc042.setSubUsage(null);    //暂时不知道数据哪里来的
//                pc042List.add(pc042);
//
//                //封装pc043
//                Pc043 pc043 = new Pc043();
//                pc043.setCompanyId(companyId);
//                pc043.setSumNo(request.getSumNo());
//                pc043.setMtlNo(usageDetail.getMtlNo());
//                pc043.setMtlName(usageDetail.getMtlName());
//                pc043.setMtlSpec(usageDetail.getMtlSpec());
//                pc043.setMtlUnit(usageDetail.getMtlUnit());
//                pc043.setMtlColor(usageDetail.getMtlColor());
//                pc043.setLotNo(request.getLotNo());
//                pc043.setLotDetail(request.getLotNo());
//                pc043.setLotType(request.getLotType());
//                //数量
//                pc043.setTtlUsage(ttlUsage);
//                pc043.setActUsage(ttlUsage);
//                pc043.setAdvanceUsage(usageDetail.getAddUsage());
//                pc043.setSubUsage(null);    //暂时不知道数据哪里来的
//                pc043List.add(pc043);
//            }
//        }
//        int count2 = summaryOperationMapper.addPc042(pc042List);
//        int count3 = summaryOperationMapper.addPc043(pc043List);
//        //6.复制给pc044
//        List<Pc044> pc044List = new ArrayList<>();
//        if (ObjectUtils.isNotEmpty(subList)) {
//            for (SdBomFitSubDto sub : subList) {
//                //贴合子材料只有有清购标识的才会汇总进去
//                Pc044 pc044 = new Pc044();
//                pc044.setCompanyId(companyId);
//                pc044.setSumNo(request.getSumNo());
//                pc044.setLotNo(request.getLotNo());
//                pc044.setLotType(request.getLotType());
//                pc044.setMtlNo(sub.getMtlNo());
//                pc044.setMtlName(sub.getMtlName());
//                pc044.setMtlUnit(sub.getMtlUnit());
//                pc044.setMtlColor(sub.getMtlColor());
//                pc044.setMtlSpec(sub.getMtlSpec());
//                pc044.setSubMtlNo(sub.getSubMtlNo());
//                pc044.setSubMtlName(sub.getSubMtlName());
//                pc044.setSubMtlUnit(sub.getSubMtlUnit());
//                pc044.setSubMtlColor(sub.getSubMtlColor());
//                pc044.setSubMtlSpec(sub.getSubMtlSpec());
//                //向上取整：数量
//                BigDecimal ttlUsage = sub.getTtlUsage();
//                // 检查ttlUsage是否为整数
//                boolean isInteger = ttlUsage.scale() <= 0 || ttlUsage.stripTrailingZeros().scale() <= 0;
//                // 如果ttlUsage不是整数，进行向上取整
//                BigDecimal roundedTtlUsage = isInteger ? ttlUsage : ttlUsage.setScale(0, RoundingMode.CEILING);
//                //填充数量
//                pc044.setTtlUsage(null);
//                pc044.setSubTtlUsage(roundedTtlUsage);
//                //贴合子材料的预加量先不管
//                pc044.setAdvanceUsage(sub.getAddUsage());
//                pc044List.add(pc044);
//            }
//        }
//        if(ObjectUtils.isNotEmpty(pc044List)){
//            int count4 = summaryOperationMapper.addPc044(pc044List);
//        }
//
//        /*三、pc042根据材料去已经下单的地方查是否下单，如果下单了就要减去用量*/
//        //查询已下单,分组查询已经下单的相同材料的总数量
//        List<PurchaseOrderDto> orderList = materialClearanceMapper.getPurchaseOrderInHzAndCyOrderMtl2(companyId,lotNo);
//
//        /*四、遍历分情况赋值*/
//        //1.订单有材料，汇总单有材料》》汇总数量-订单数量 = 目前数量
//        //a.如果大于0显示正数，同时备注已下单的订单数量
//                //把订购的材料写入到汇总表，请购单号，数量，请购标识
//                //此材料不变，只变显示的材料用量就是：汇总数量-订单数量
//        //b.如果等于0，标识这个材料已经买完了
//               //把该材料写入到汇总表，请购单号，数量，请购标识
//        //c.如果小于O，代表这个材料买多了，现在不需要
//                //把订购的材料写入到汇总表，请购单号，数量，请购标识
//                //此材料不变，只变显示的材料用量就是：汇总数量-订单数量,复数，备注代表这个材料买多了，现在不需要
//
//        //2.订单没有材料，汇总单有材料》》不用管
//
//        //3.订单有材料，汇总单没有材料》》
//        //a.在汇总表里面备注:订单有材料，新的汇总单没有这个材料
//        //b.还是把这个材料写入到汇总表，请购单号，数量，请购标识
//        List<Pc044> pc044List = new ArrayList<>();
//        Pc042 pc0421 = new Pc042();
//        for (Pc042 pc042 : pc042List) {
//
//        }
//
//
//        if (count > 0 && count1 > 0 && count2 > 0 && count3 > 0 ) {
//            return ResponseInfo.ok("汇总作业完成，汇总号："+ request.getSumNo());
//        } else {
//            throw new ServiceErrorException("汇总作业失败");
//        }
//    }

    /**
     * 采购汇总作业：数据平移
     * @param lotNo
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo summaryDataExchange2(String lotNo) {
        String companyId = UserIdThread.get().getCompanyId();
        SummaryRequest request = new SummaryRequest();
        request.setLotNo(lotNo);
        List<SummaryMaterialsDto> list = summaryOperationMapper.summaryDataExchange2(companyId, request);
        if(ObjectUtils.isEmpty(list)){
            throw new ServiceErrorException("没有找到数据");
        }

         Pc040 pc040 = summaryOperationMapper.getPc040Two(companyId, lotNo);
        if(pc040.getCfmUser() != null && pc040.getCfmUser().equals("LTF")){
            throw new ServiceErrorException(lotNo + "已经数据平移");
        }


//        try {
            for (SummaryMaterialsDto dto : list) {
                BigDecimal ttlUsage = dto.getTtlUsage() != null ? dto.getTtlUsage() : BigDecimal.ZERO;
                BigDecimal purQty = dto.getPurQty();
                //1.不为空
                if (dto.getPurQty() != null) {
                    /*比较*/
                    //向上取整：数量
                    // 检查ttlUsage是否为整数
                    boolean isInteger = purQty.scale() <= 0 || purQty.stripTrailingZeros().scale() <= 0;
                    // 如果ttlUsage不是整数，进行向上取整
//                    purQty = isInteger ? purQty : purQty.setScale(0, RoundingMode.CEILING);
                    //比较
                    int result = ttlUsage.compareTo(dto.getPurQty());
                    // 计算差值
                    BigDecimal difference = ttlUsage.subtract(purQty);

                    if (result > 0) {
                        /*1.大于的情况*/
                        // 下单了，现在还有可以继续下单
                        //b.把原材料数量修改减少
                        Pc042 date2 = new Pc042();
                        date2.setCompanyId(companyId);
                        date2.setSumNo(request.getSumNo());
                        date2.setMtlNo(dto.getMtlNo());
                        date2.setMtlName(dto.getMtlName());
                        date2.setMtlSpec(dto.getMtlSpec());
                        date2.setMtlUnit(dto.getMtlUnit());
                        date2.setMtlColor(dto.getMtlColor());
                        date2.setLotDetail(request.getLotNo());
                        //数量
                        date2.setTtlUsage(difference);
                        date2.setActUsage(difference);
                        //备注
                        date2.setRemark(dto.getReqNo() + "，该材料应下单:" + ttlUsage+"，该材料已下单:" + purQty+"，剩余：" + difference);
                        int count1 = summaryOperationMapper.updatePc042Two2(date2);
                        log.info("更新:材料汇总指令 pc042 成功，影响行数：{}", count1);

                        //a.把这个材料新增到汇总
//                        Pc042 date = new Pc042();
//                        date.setCompanyId(companyId);
//                        date.setSumNo(request.getSumNo());
//                        date.setMtlNo(dto.getMtlNo());
//                        date.setMtlName(dto.getMtlName());
//                        date.setMtlSpec(dto.getMtlSpec());
//                        date.setMtlUnit(dto.getMtlUnit());
//                        date.setMtlColor(dto.getMtlColor());
//                        date.setLotDetail(request.getLotNo());
//                        date.setReqNo(dto.getReqNo());
//                        date.setPurUserName(dto.getSysUser());
//                        date.setSumNo(dto.getSumNo());
//                        //数量 + 在sql写入订购标识
//                        date.setTtlUsage(purQty);
//                        date.setActUsage(purQty);
//                        date.setRemark(dto.getReqNo() + "，该材料在汇总前已下单:" + purQty);
//                        int count2 = summaryOperationMapper.addPc042Two(date);
                    } else if (result < 0) {
                        /*2.小于的情况*/
                        // 下单了，下多了
                        //b.把原材料数量修改减少，且备注
                        Pc042 date2 = new Pc042();
                        date2.setCompanyId(companyId);
                        date2.setSumNo(request.getSumNo());
                        date2.setMtlNo(dto.getMtlNo());
                        date2.setMtlName(dto.getMtlName());
                        date2.setMtlSpec(dto.getMtlSpec());
                        date2.setMtlUnit(dto.getMtlUnit());
                        date2.setMtlColor(dto.getMtlColor());
                        date2.setLotDetail(request.getLotNo());
                        date2.setReqNo(dto.getReqNo());
                        date2.setPurUserName(dto.getSysUser());
                        //数量 + 在sql写入订购标识
                        date2.setTtlUsage(difference);
                        date2.setActUsage(difference);
                        //备注
                        date2.setRemark(dto.getReqNo() + "，该材料应下单:" + ttlUsage+"，该材料已下单:" + purQty+"，差异：" + difference);
                        int count1 = summaryOperationMapper.updatePc042Two(date2);
                        log.info("更新:材料汇总指令 pc042 成功，影响行数：{}", count1);
                        //a.把这个材料新增到汇总
                        //先不写这种情况，退单时候再说

                        System.out.println("purQty 小于 ttlUsage");
                    } else if (result == 0) {
                        /*2.等于的情况*/
                        //走修改，加单号
                        Pc042 date2 = new Pc042();
                        date2.setCompanyId(companyId);
                        date2.setSumNo(request.getSumNo());
                        date2.setMtlNo(dto.getMtlNo());
                        date2.setMtlName(dto.getMtlName());
                        date2.setMtlSpec(dto.getMtlSpec());
                        date2.setMtlUnit(dto.getMtlUnit());
                        date2.setMtlColor(dto.getMtlColor());
                        date2.setLotDetail(request.getLotNo());
                        date2.setReqNo(dto.getReqNo());
                        date2.setPurUserName(dto.getSysUser());
                        date2.setTtlUsage(ttlUsage);
                        date2.setActUsage(ttlUsage);
                        //备注+ 在sql写入订购标识
                        date2.setRemark(dto.getReqNo() + "，该材料应下单:" + ttlUsage+"，该材料已下单:" + purQty+"，剩余：" + difference);
                        int count1 = summaryOperationMapper.updatePc042Two(date2);
                    }
                }
                //2.PurQty为空或者为0，说明该材料没有下单,不用管
            }
            summaryOperationMapper.updatePc040Two(companyId, lotNo);
            return  ResponseInfo.ok();

//       }catch (Exception e){
//            log.error("summaryOperationBatch error:{}",e.getMessage());
//           throw  new ServiceErrorException(e.getMessage());
//        }

    }

    /**
     * 采购汇总作业：数据平移-批量
     * @return
     */
    @Override
    public ResponseInfo summaryDataExchange3(List<String> list1) {
        String companyId = UserIdThread.get().getCompanyId();
        if(ObjectUtils.isNotEmpty(list1)){
            for (String lotNo : list1) {

                SummaryRequest request = new SummaryRequest();
                request.setLotNo(lotNo);
                List<SummaryMaterialsDto> list = summaryOperationMapper.summaryDataExchange2(companyId, request);
                if(ObjectUtils.isEmpty(list)){
                    throw new ServiceErrorException("没有找到数据");
                }

//        try {
                for (SummaryMaterialsDto dto : list) {
                    BigDecimal ttlUsage = dto.getTtlUsage() != null ? dto.getTtlUsage() : BigDecimal.ZERO;
                    BigDecimal purQty = dto.getPurQty();
                    //1.不为空
                    if (dto.getPurQty() != null) {
                        /*比较*/
                        //向上取整：数量
                        // 检查ttlUsage是否为整数
                        boolean isInteger = purQty.scale() <= 0 || purQty.stripTrailingZeros().scale() <= 0;
                        // 如果ttlUsage不是整数，进行向上取整
//                    purQty = isInteger ? purQty : purQty.setScale(0, RoundingMode.CEILING);
                        //比较
                        int result = ttlUsage.compareTo(dto.getPurQty());
                        // 计算差值
                        BigDecimal difference = ttlUsage.subtract(purQty);

                        if (result > 0) {
                            /*1.大于的情况*/
                            // 下单了，现在还有可以下单de
                            //b.把原材料数量修改减少
                            Pc042 date2 = new Pc042();
                            date2.setCompanyId(companyId);
                            date2.setSumNo(request.getSumNo());
                            date2.setMtlNo(dto.getMtlNo());
                            date2.setMtlName(dto.getMtlName());
                            date2.setMtlSpec(dto.getMtlSpec());
                            date2.setMtlUnit(dto.getMtlUnit());
                            date2.setMtlColor(dto.getMtlColor());
                            date2.setLotDetail(request.getLotNo());
                            //数量
                            date2.setTtlUsage(difference);
                            date2.setActUsage(difference);
                            //备注
                            date2.setRemark(dto.getReqNo() + "，该材料已下单:" + purQty+"，剩余：" + difference);
                            int count1 = summaryOperationMapper.updatePc042Two2(date2);
                            log.info("更新:材料汇总指令 pc042 成功，影响行数：{}", count1);

                            //a.把这个材料新增到汇总
//                        Pc042 date = new Pc042();
//                        date.setCompanyId(companyId);
//                        date.setSumNo(request.getSumNo());
//                        date.setMtlNo(dto.getMtlNo());
//                        date.setMtlName(dto.getMtlName());
//                        date.setMtlSpec(dto.getMtlSpec());
//                        date.setMtlUnit(dto.getMtlUnit());
//                        date.setMtlColor(dto.getMtlColor());
//                        date.setLotDetail(request.getLotNo());
//                        date.setReqNo(dto.getReqNo());
//                        date.setPurUserName(dto.getSysUser());
//                        date.setSumNo(dto.getSumNo());
//                        //数量 + 在sql写入订购标识
//                        date.setTtlUsage(purQty);
//                        date.setActUsage(purQty);
//                        date.setRemark(dto.getReqNo() + "，该材料在汇总前已下单:" + purQty);
//                        int count2 = summaryOperationMapper.addPc042Two(date);
                        } else if (result < 0) {
                            /*2.小于的情况*/
                            // 下单了，下多了
                            //b.把原材料数量修改减少，且备注
                            Pc042 date2 = new Pc042();
                            date2.setCompanyId(companyId);
                            date2.setSumNo(request.getSumNo());
                            date2.setMtlNo(dto.getMtlNo());
                            date2.setMtlName(dto.getMtlName());
                            date2.setMtlSpec(dto.getMtlSpec());
                            date2.setMtlUnit(dto.getMtlUnit());
                            date2.setMtlColor(dto.getMtlColor());
                            date2.setLotDetail(request.getLotNo());
                            date2.setReqNo(dto.getReqNo());
                            date2.setPurUserName(dto.getSysUser());
                            //数量 + 在sql写入订购标识
                            date2.setTtlUsage(difference);
                            date2.setActUsage(difference);
                            //备注
                            date2.setRemark(dto.getReqNo() + "这个材料现在不需要了，但是已经下单:" + purQty +"需要退回：" + difference);
                            int count1 = summaryOperationMapper.updatePc042Two(date2);
                            log.info("更新:材料汇总指令 pc042 成功，影响行数：{}", count1);
                            //a.把这个材料新增到汇总
                            //先不写这种情况，退单时候再说

                            System.out.println("purQty 小于 ttlUsage");
                        } else if (result == 0) {
                            /*2.等于的情况*/
                            //走修改，加单号
                            Pc042 date2 = new Pc042();
                            date2.setCompanyId(companyId);
                            date2.setSumNo(request.getSumNo());
                            date2.setMtlNo(dto.getMtlNo());
                            date2.setMtlName(dto.getMtlName());
                            date2.setMtlSpec(dto.getMtlSpec());
                            date2.setMtlUnit(dto.getMtlUnit());
                            date2.setMtlColor(dto.getMtlColor());
                            date2.setLotDetail(request.getLotNo());
                            date2.setReqNo(dto.getReqNo());
                            date2.setPurUserName(dto.getSysUser());
                            date2.setTtlUsage(ttlUsage);
                            date2.setActUsage(ttlUsage);
                            //备注+ 在sql写入订购标识
                            date2.setRemark(dto.getReqNo() + "，该材料已下单:" + purQty);
                            int count1 = summaryOperationMapper.updatePc042Two(date2);
                        }
                    }
                    //2.PurQty为空或者为0，说明该材料没有下单,不用管
                }
                return  ResponseInfo.ok();

            }
        }
        return null;
    }



//    /**
//     * 采购汇总作业：数据平移3
//     * @param lotNo
//     * @return
//     */
//    @Override
//    @Transactional
//    public ResponseInfo summaryDataExchange3(String lotNo) {
//        String companyId = UserIdThread.get().getCompanyId();
//        SummaryRequest request = new SummaryRequest();
//        request.setLotNo(lotNo);
//        List<SummaryMaterialsDto> list = summaryOperationMapper.summaryDataExchange2(companyId, request);
//        if(ObjectUtils.isEmpty(list)){
//            throw new ServiceErrorException("没有找到数据");
//        }
//
////        try {
//        for (SummaryMaterialsDto dto : list) {
//            BigDecimal ttlUsage = dto.getTtlUsage() != null ? dto.getTtlUsage() : BigDecimal.ZERO;
//            BigDecimal purQty = dto.getPurQty();
//            //1.不为空
//            if (dto.getPurQty() != null) {
//                /*比较*/
//                //向上取整：数量
//                // 检查ttlUsage是否为整数
//                boolean isInteger = purQty.scale() <= 0 || purQty.stripTrailingZeros().scale() <= 0;
//                // 如果ttlUsage不是整数，进行向上取整
////                    purQty = isInteger ? purQty : purQty.setScale(0, RoundingMode.CEILING);
//                //比较
//                int result = ttlUsage.compareTo(dto.getPurQty());
//                // 计算差值
//                BigDecimal difference = ttlUsage.subtract(purQty);
//
//                if (result > 0) {
//                    /*1.大于的情况*/
//                    // 下单了，现在还有可以下单de
//                    //b.把原材料数量修改减少
//                    Pc042 date2 = new Pc042();
//                    date2.setCompanyId(companyId);
//                    date2.setSumNo(request.getSumNo());
//                    date2.setMtlNo(dto.getMtlNo());
//                    date2.setMtlName(dto.getMtlName());
//                    date2.setMtlSpec(dto.getMtlSpec());
//                    date2.setMtlUnit(dto.getMtlUnit());
//                    date2.setMtlColor(dto.getMtlColor());
//                    date2.setLotDetail(request.getLotNo());
//                    //数量
//                    date2.setTtlUsage(difference);
//                    date2.setActUsage(difference);
//                    //备注
//                    date2.setRemark(dto.getReqNo() + "，该材料已下单:" + purQty+"，剩余：" + difference);
//                    int count1 = summaryOperationMapper.updatePc042Two2(date2);
//                    log.info("更新:材料汇总指令 pc042 成功，影响行数：{}", count1);
//
//                    PcLotUsageChg pcLotUsageChg = new PcLotUsageChg();
//                    pcLotHeadMapper.addPcLotUsageChgList(pcLotUsageChgList);
//
//                } else if (result < 0) {
//                    /*2.小于的情况*/
//                    // 下单了，下多了
//                    //b.把原材料数量修改减少，且备注
//                    Pc042 date2 = new Pc042();
//                    date2.setCompanyId(companyId);
//                    date2.setSumNo(request.getSumNo());
//                    date2.setMtlNo(dto.getMtlNo());
//                    date2.setMtlName(dto.getMtlName());
//                    date2.setMtlSpec(dto.getMtlSpec());
//                    date2.setMtlUnit(dto.getMtlUnit());
//                    date2.setMtlColor(dto.getMtlColor());
//                    date2.setLotDetail(request.getLotNo());
//                    date2.setReqNo(dto.getReqNo());
//                    date2.setPurUserName(dto.getSysUser());
//                    //数量 + 在sql写入订购标识
//                    date2.setTtlUsage(difference);
//                    date2.setActUsage(difference);
//                    //备注
//                    date2.setRemark(dto.getReqNo() + "这个材料现在不需要了，但是已经下单:" + purQty +"需要退回：" + difference);
//                    int count1 = summaryOperationMapper.updatePc042Two(date2);
//                    log.info("更新:材料汇总指令 pc042 成功，影响行数：{}", count1);
//                    //a.把这个材料新增到汇总
//                    //先不写这种情况，退单时候再说
//
//                    PcLotUsageChg pcLotUsageChg = new PcLotUsageChg();
//                    pcLotHeadMapper.addPcLotUsageChg(pcLotUsageChg);
//                } else if (result == 0) {
//                    /*2.等于的情况*/
//                    //走修改，加单号
//                    Pc042 date2 = new Pc042();
//                    date2.setCompanyId(companyId);
//                    date2.setSumNo(request.getSumNo());
//                    date2.setMtlNo(dto.getMtlNo());
//                    date2.setMtlName(dto.getMtlName());
//                    date2.setMtlSpec(dto.getMtlSpec());
//                    date2.setMtlUnit(dto.getMtlUnit());
//                    date2.setMtlColor(dto.getMtlColor());
//                    date2.setLotDetail(request.getLotNo());
//                    date2.setReqNo(dto.getReqNo());
//                    date2.setPurUserName(dto.getSysUser());
//                    date2.setTtlUsage(ttlUsage);
//                    date2.setActUsage(ttlUsage);
//                    //备注+ 在sql写入订购标识
//                    date2.setRemark(dto.getReqNo() + "，该材料已下单:" + purQty);
//                    int count1 = summaryOperationMapper.updatePc042Two(date2);
//                }
//            }
//            //2.PurQty为空或者为0，说明该材料没有下单,不用管
//        }
//        return  ResponseInfo.ok();
//
////       }catch (Exception e){
////            log.error("summaryOperationBatch error:{}",e.getMessage());
////           throw  new ServiceErrorException(e.getMessage());
////        }
//
//        return null;
//    }

    /**
     * 获得时间戳+自增数据
     * @param key  根据key获得自增数据
     * @param length 自增长度
     * @param timezone 想要获得的时间戳保留字段 yyMM yyyy-MM-dd HH:mm:ss
     */
    private String generatePrefix(String key,String length,String timezone) {
        //根据key获得自增数据
        RedisAtomicInteger ato = new RedisAtomicInteger(key, redisService.getConnectionFactory());
        String l = "%0" + length + "d"; //%07d
        String value = String.format(l, ato.getAndIncrement());
        redisService.setOutTime(key);
        //时间戳
        LocalDateTime now = LocalDateTime.now();
        String time = now.format(DateTimeFormatter.ofPattern(timezone));
        return time + value;
    }
}

